package vben.core.module.sys.coop.user;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import vben.core.common.mvc.service.BaseMainService;
import vben.core.common.utils.lang.SecureUtils;
import vben.core.module.sys.coop.cate.SysCoopCate;
import vben.core.module.sys.coop.cate.SysCoopCateRepo;
import vben.core.module.sys.coop.corp.SysCoopCorp;
import vben.core.module.sys.coop.corp.SysCoopCorpRepo;
import vben.core.module.sys.org.root.SysOrg;
import vben.core.module.sys.org.root.SysOrgRepo;
import vben.core.module.sys.org.user.PacodPo;
import vben.core.common.utils.lang.IdUtils;

import javax.annotation.PostConstruct;

@Service
public class SysCoopUserService extends BaseMainService<SysCoopUser> {

    public String insertx(SysCoopUser user){
        user.setId(IdUtils.getUID());
        if(user.getCorp()!=null){
            SysCoopCorp corp= cropRepo.getOne(user.getCorp().getId());
            SysCoopCate cate= cateRepo.getOne(corp.getCatid());
            user.setTier(cate.getTier()+corp.getId()+"x"+user.getId()+"x");
        }else{
            user.setTier("x"+user.getId()+"x");
        }
        user.setPacod(SecureUtils.passwordEncrypt(user.getPacod()));
        String id= insert(user);
        SysOrg sysOrg=new SysOrg(id,user.getName(),256);
        orgRepo.save(sysOrg);
        return id;
    }

    public String updatex(SysCoopUser user){
        if(user.getCorp()!=null){
            SysCoopCorp corp= cropRepo.getOne(user.getCorp().getId());
            SysCoopCate cate= cateRepo.getOne(corp.getCatid());
            user.setTier(cate.getTier()+"x"+corp.getId()+"x"+user.getId()+"x");
        }else{
            user.setTier("x"+user.getId()+"x");
        }
        update(user);
        SysOrg sysOrg=new SysOrg(user.getId(),user.getName(),256);
        orgRepo.save(sysOrg);
        return user.getId();
    }

    public int deletex(String[] ids) {
        for (String id : ids) {
            repo.deleteById(id);
            orgRepo.deleteById(id);
        }
        return ids.length;
    }

    public void pacod(PacodPo po) {
        po.setPacod(SecureUtils.passwordEncrypt(po.getPacod()));
        String sql="update sys_coop_user set pacod=? where id=?";
        jdbcDao.update(sql,po.getPacod(),po.getId());
    }

    //----------bean注入------------
    @Autowired
    private SysOrgRepo orgRepo;

    @Autowired
    private SysCoopCorpRepo cropRepo;

    @Autowired
    private SysCoopCateRepo cateRepo;

    @Autowired
    private SysCoopUserRepo repo;

    @PostConstruct
    public void initDao() {
        super.setRepo(repo);
    }

}
